//
// Created by Jeffrey Wei on 2022/10/11.
// App的上下文,包含一些常用功能

import Foundation
import UIKit
import URLNavigator

public let AppContext = Context.shared

public class Context: NSObject {
    @objc public static let shared = Context()
    /// 导航器,可直接跳转控制器
    public let navigator = Navigator()
}

/// 控制器,window相关
public extension Context {
    /// 应用的window,若解包失败则必然是程序初始化window还没成功就调用
    var window: UIWindow! {
        (UIApplication.shared.delegate as? CoreAppDelegate)?.window
    }

    /// 重置window,在此之前将rootViewController的判断逻辑改变即可
    @objc func resetWindow() {
        window.rootViewController = (UIApplication.shared.delegate as? CoreAppDelegate)?.rootViewController
    }

    @objc var topMost: UIViewController? {
        UIViewController.topMost
    }
}

/// 微服务相关
public extension Context {
    /// 寻找一个微服务,找不到返回nil
    func findService<S: Service>(_ serviceType: S.Type) -> S? {
        let delegate = UIApplication.shared.delegate as? CoreAppDelegate
        let existService = delegate?.services.first {
            type(of: $0) == serviceType
        } as? S
        return existService
    }
}
